# _*_ coding:utf-8 _*_
from http.server import HTTPServer, BaseHTTPRequestHandler
import io, shutil
from urllib import parse
import os;
import subprocess;
import json
import time;
from face_service import face_service
from MyEncoder import MyEncoder


class MyHttpHandler(BaseHTTPRequestHandler, face_service):

    def _get_value(self, params, key):
        if key in params:
            return params[key][0];
        return None;

    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def successJson(self, data=[], msg=""):
        result_data = {'code': 200, 'msg': msg, 'data': data};
        self._response_data(json.dumps(result_data, cls=MyEncoder))

    def failJson(self, msg='操作失败', code=0):
        result_data = {'code': code, 'msg': msg, 'data': ''};
        self._response_data(json.dumps(result_data, cls=MyEncoder))

    def _response_data(self, data):
        enc = "UTF-8"
        encoded = data.encode(enc)
        f = io.BytesIO()
        f.write(encoded)
        f.seek(0)

        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=%s" % enc)
        self.send_header("Content-Length", str(len(encoded)))
        self.end_headers()
        shutil.copyfileobj(f, self.wfile)

    def do_GET(self):
        self.queryString = '';
        result_data = {"nrof_faces": 0, "bounding_boxes": "", "img_path": ""};

        if "?" in self.path:
            self.queryString = parse.unquote(self.path.split('?', 1)[1])
            params = parse.parse_qs(self.queryString)

            url = self._get_value(params, 'url');
            is_prview = self._get_value(params, 'prview');

            if url is None or url == '':
                return self.failJson('url 不能为空');

            img = face_service._get_img(url);
            if img is None:
                return self.failJson(url + '获取图片错误');

            # 获取人脸结果
            nrof_faces, bounding_boxes = face_service.detect_face(img)

            # 生成图片地址
            if is_prview and nrof_faces > 0:
                img_path = "img/" + str(int(time.time())) + ".jpg";
                face_service.image_save(img, bounding_boxes, img_path);
                result_data['img_path'] = img_path

            # 组装数据返回
            result_data['nrof_faces'] = nrof_faces;
            result_data['bounding_boxes'] = bounding_boxes;

        print(result_data);
        return self.successJson(result_data)


face_service = face_service();
httpd = HTTPServer(('', 8000), MyHttpHandler, face_service)
print("Server started on 127.0.0.1,port 8000.....")
httpd.serve_forever()
